package com.redwood.report.adapter;

import android.content.Intent;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.MotionEvent;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.XAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.redwood.report.R;
import com.redwood.report.activity.LishiChaXunActivity;
import com.redwood.report.activity.ReportActivity;
import com.redwood.report.entity.BaoBiaoBeen;
import com.redwood.report.entity.BarDataBeen;
import com.redwood.report.entity.HistoryBarChartBeen;
import com.redwood.report.entity.HistoryPieChartBeen;
import com.redwood.report.entity.HistoryTipstBeen;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 历史item
 *
 * Created by Supeng on 2018/8/23.
 */
//Caption been
public class HistoryItemAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity,BaseViewHolder> {
    public static final int TYPE_LEVEL_1 = 0;
    public static final int TYPE_LEVEL_2 = 1;
    public static final int TYPE_LEVEL_3 = 2;
    private float rawx=0;
    public List<String> xvalue=new ArrayList<>();
    public HistoryItemAdapter(List data) {
        super(data);
        addItemType(TYPE_LEVEL_1, R.layout.layout_history_item);
        addItemType(TYPE_LEVEL_2, R.layout.layout_historypie_item);
        addItemType(TYPE_LEVEL_3, R.layout.layout_historybar_item);
    }
    @Override
    protected void convert(final BaseViewHolder holder, MultiItemEntity itemTemp) {
        switch (holder.getItemViewType()) {
            case TYPE_LEVEL_1:
                HistoryTipstBeen historyTipstBeen= (HistoryTipstBeen) itemTemp;
                holder.setText(R.id.tv_yunxingh,historyTipstBeen.getZaixianh()+"");
                holder.setText(R.id.tv_daijih,historyTipstBeen.getDaijih()+"");
                holder.setText(R.id.tv_lixianh,historyTipstBeen.getLixianh()+"");
                holder.setText(R.id.tv_guzhangh,historyTipstBeen.getGuzhangh()+"");
               break;
            case TYPE_LEVEL_2:
                HistoryPieChartBeen historyPieChartBeen= (HistoryPieChartBeen) itemTemp;
                PieChart chart_jitai=holder.getView(R.id.chart_jitai);
                initChartOne(chart_jitai);
                setTSData(chart_jitai,historyPieChartBeen.getZaixian(),historyPieChartBeen.getLixian(),historyPieChartBeen.getJingdao(),historyPieChartBeen.getDaiji());
                break;
            case TYPE_LEVEL_3:
                HistoryBarChartBeen historyBarChartBeen= (HistoryBarChartBeen) itemTemp;
                BarChart chart_barchart_jitai=holder.getView(R.id.chart_barchart_jitai);
                initChartSet(chart_barchart_jitai,historyBarChartBeen.getHashMapName());
//               int[] myColor= new int[]{mContext.getResources().getColor(R.color.main_green)
//                        ,mContext.getResources().getColor(R.color.main_red)
//                        ,mContext.getResources().getColor(R.color.main_gray),
//                        mContext.getResources().getColor(R.color.main_yellow)};
//
//                LinkedHashMap<String,List<BarDataBeen>> hashMapBarList=new LinkedHashMap<>();
//                Random ran2 = new Random(4);
//                for(int k=14;k>0;k--) {
//                    List<BarDataBeen> barDataBeenList = new ArrayList<>();
//                    //最小0.05f
//                    for (int i = 1; i < 25; i++) {
//                        BarDataBeen barDataBeen = new BarDataBeen();
//                        if (i % 2 == 0) {
//                            barDataBeen.setTimer(0.5f);
//                        } else {
//                            barDataBeen.setTimer(1.5f);
//                        }
//                        // Log.i("supeng",""+ran2.nextInt(4));
//                        barDataBeen.setColor(myColor[ran2.nextInt(4)]);
//                        barDataBeenList.add(barDataBeen);
//                    }
//                    hashMapBarList.put("M000"+k,barDataBeenList);
//                }
                initChart(historyBarChartBeen.getLinkedHashMap(),chart_barchart_jitai);
                break;
        }

    }

    private void initChart( LinkedHashMap<String,List<BarDataBeen>> hashMapBarList, BarChart chart_barchart_jitai){
        List<BarEntry> yvalue=new ArrayList<>();
        int index=0;
        xvalue.clear();
        List<Integer> colorArrList=new ArrayList<>();
        for(Map.Entry<String, List<BarDataBeen>> entry: hashMapBarList.entrySet()) {
            List<BarDataBeen>  barDataBeenList=entry.getValue();
            float[] valueArr = new float[barDataBeenList.size()];
            for (int i = 0; i < barDataBeenList.size(); i++) {
                valueArr[i] = barDataBeenList.get(i).getTimer();
                colorArrList.add(barDataBeenList.get(i).getColor());
            }
            //敲黑板啦！！这里才是重点部分，可以添加一个float数组，让它变成StackBar
            yvalue.add(new BarEntry(valueArr,index++));
            xvalue.add(entry.getKey());

        }
        BarDataSet set=new BarDataSet(yvalue,"");
        set.setColors(colorArrList);//set会循环这里的颜色进行添加
        set.setDrawValues(false);
        BarData data=new BarData(xvalue,set);
        chart_barchart_jitai.setData(data);

    }
    private void initChartSet(final BarChart chart_barchart_jitai, final HashMap<String, String> hashMap) {

        YAxis yAxis = chart_barchart_jitai.getAxisLeft();
        yAxis.setAxisMaxValue(24);
        yAxis.setLabelCount(9,false);
        yAxis.setAxisMinValue(0);
        yAxis.setTextColor(mContext.getResources().getColor(R.color.bwhite));
        YAxis yAxist = chart_barchart_jitai.getAxisRight();
        yAxist.setAxisMaxValue(24);
        yAxist.setLabelCount(24,false);
        yAxist.setAxisMinValue(0);
        yAxist.setDrawLabels(false);
        chart_barchart_jitai.getLegend().setEnabled(false);
        chart_barchart_jitai.animateY(1500);
        chart_barchart_jitai.setDescription("");
        chart_barchart_jitai.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        chart_barchart_jitai.getXAxis().setTextColor(mContext.getResources().getColor(R.color.bwhite));

        chart_barchart_jitai.getXAxis().setValueFormatter(new XAxisValueFormatter() {
            @Override
            public String getXValue(String s, int i, ViewPortHandler viewPortHandler) {
                return hashMap.get(s);
            }
                                                          });


        chart_barchart_jitai.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry entry, int i, Highlight highlight) {
                if(rawx>0&&rawx<70){

                }else{
                    return;
                }
                Intent intent=new Intent(mContext, ReportActivity.class);
                intent.putExtra("title",hashMap.get(xvalue.get(entry.getXIndex())));
                intent.putExtra("bianhao",xvalue.get(entry.getXIndex()));
                intent.putExtra("day", LishiChaXunActivity.dateTimerStr);
                mContext.startActivity(intent);
            }

            @Override
            public void onNothingSelected() {

            }
        });
        chart_barchart_jitai.setOnChartGestureListener(new OnChartGestureListener() {
            @Override
            public void onChartGestureStart(MotionEvent motionEvent, ChartTouchListener.ChartGesture chartGesture) {
                rawx=motionEvent.getRawX();
            }

            @Override
            public void onChartGestureEnd(MotionEvent motionEvent, ChartTouchListener.ChartGesture chartGesture) {


            }

            @Override
            public void onChartLongPressed(MotionEvent motionEvent) {

            }

            @Override
            public void onChartDoubleTapped(MotionEvent motionEvent) {

            }

            @Override
            public void onChartSingleTapped(MotionEvent motionEvent) {

            }

            @Override
            public void onChartFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {

            }

            @Override
            public void onChartScale(MotionEvent motionEvent, float v, float v1) {

            }

            @Override
            public void onChartTranslate(MotionEvent motionEvent, float v, float v1) {

            }
        });

                //.setDrawLabels(false);

        //.setPosition(XAxis.XAxisPosition.BOTTOM);
        //.setDrawLabels(false);
    }

    private void setTSData(PieChart chart_jitai,float yunxing,float lixian,float jinggao,float daiji) {
        int allCount=(int)(yunxing+lixian+jinggao+daiji);
        chart_jitai.setCenterText(generateCenterText());
        //设置标题
        ArrayList<String> titles = new ArrayList<>();
        ArrayList<Entry> entrys = new ArrayList<>();
        int index=0;
        List<Integer> colors =new ArrayList<>();
        if(yunxing!=0){
            titles.add(mContext.getResources().getString(R.string.yunxing)+(int)((yunxing/allCount)*1000)/10f+"%");
            if(yunxing<0.01){
                yunxing=0.01f;
            }
            entrys.add(new Entry(yunxing, index));
            colors.add(mContext.getResources().getColor(R.color.main_green));
            index++;
        }
        if(lixian!=0){
            titles.add(mContext.getResources().getString(R.string.lixian)+(int)((lixian/allCount)*1000)/10f+"%");
            if(lixian<0.01){
                lixian=0.01f;
            }
            entrys.add(new Entry(lixian, index));
            colors.add(mContext.getResources().getColor(R.color.main_gray));
            index++;
        }
        if(jinggao!=0){
            titles.add(mContext.getResources().getString(R.string.jinggao)+(int)((jinggao/allCount)*1000)/10f+"%");
            if(jinggao<0.01){
                jinggao=0.01f;
            }
            entrys.add(new Entry(jinggao, index));
            colors.add(mContext.getResources().getColor(R.color.main_red));
            index++;
        }
        if(daiji!=0){

            titles.add(mContext.getResources().getString(R.string.daiji)+(int)((daiji/allCount)*1000)/10f+"%");
            if(daiji<0.01){
                daiji=0.01f;
            }
            entrys.add(new Entry(daiji, index));
            colors.add(mContext.getResources().getColor(R.color.main_yellow));
            index++;
        }

        //饼图数据集
        PieDataSet dataset = new PieDataSet(entrys, "");
        //设置饼状图Item之间的间隙
        dataset.setSliceSpace(5f);
        dataset.setDrawValues(false);
        //饼图Item被选中时变化的距离
        dataset.setSelectionShift(5f);
//        dataset.setValueFormatter(new ValueFormatter() {//圆环内文字设置
//            @Override
//            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
//                int n = (int) value;
//
//                String str = n + "台";
//                if (n == 0) {
//                    str = "";
//                }
//                return str;
//            }
//        });
        //颜色填充
        dataset.setColors(colors);
        //数据填充
        PieData piedata = new PieData(titles,dataset);
        //设置饼图上显示数据的字体大小
        piedata.setValueTextSize(12);
        piedata.setValueTextColor(mContext.getResources().getColor(R.color.bwhite));
        chart_jitai.setData(piedata);
        chart_jitai.invalidate();
    }
    /**
     * 中间文字绘制
     *
     * @param
     * @return
     */
    private SpannableString generateCenterText() {
       // String total = Integer.toString(sum);
        SpannableString s = new SpannableString("设备运行情况");
      //  s.setSpan(new RelativeSizeSpan(3f), 0, total.length(), 0);
      //  s.setSpan(new ForegroundColorSpan(Color.rgb(88, 146, 240)), 0, total.length(), 0);
        s.setSpan(new ForegroundColorSpan(Color.rgb(153, 153, 153)), 0, s.length(), 0);
        return s;
    }
    private void initChartOne(PieChart chart) {
        //设置是否可转动
        chart.setRotationEnabled(false);
        //设置X轴的动画
        chart.animateX(1000);
        //使用百分比
        chart.setUsePercentValues(true);
        //设置图列可见
        chart.getLegend().setEnabled(false);
        chart.setDrawHoleEnabled(true);
        chart.setHoleColor(mContext.getResources().getColor(R.color.transt));
        chart.setDrawSliceText(true);
        chart.setDescription("");
        chart.setBackgroundColor(mContext.getResources().getColor(R.color.blueColorAppKey));
        chart.setCenterTextSize(12f);//设置中间文字中大小

    }
    public void setText(TextView tvCount,String context,String img) {
        String counStr="";
        if(!TextUtils.isEmpty(img)){
            String[] arrimgs=img.split("\\^");
            counStr=context + "照片("+arrimgs.length+")";
            SpannableStringBuilder style = new SpannableStringBuilder(counStr);
            style.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.blueColorAppKey)), context.length(), counStr.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //颜色
            tvCount.setText(style);
        }else{
            tvCount.setText(context);
        }

    }
}
